//
//  HMDrugs.swift
//  HealthMonitoring
//
//  Created by YTYanK on 16/02/2019.
//  Copyright © 2019 YTYanK. All rights reserved.
//

import UIKit
import SwiftyJSON

class HMDrugs: HMViewController {

    
    let addBtn =  UIButton()
    let input = UITextField()
    let describe = UILabel()
    let empty = UIButton()
    var drugsBlock:((_ value:String) ->(Void))?
    
    var item: OptionItemView = OptionItemView(self, json: [])
    
    override func setupView() {
        self.title = "添加药品"
        view.backgroundColor = UIColor.white
        
        
        view.addSubview(input)
        view.addSubview(addBtn)
        view.addSubview(describe)
        view.addSubview(empty)
        
        let subView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: 5, height: 5))
        
        input.layer.cornerRadius = 6
        input.layer.borderColor = configure.shareConfigure.HMColor3.cgColor
        input.layer.borderWidth = 1
        input.leftView = subView
        input.leftViewMode = UITextField.ViewMode.always
        input.topAlign(view: view, predicate: "20")
        input.leadingAlign(view: view, predicate: "10")
        input.width(view: view, predicate: "*0.75")
        input.heightConstrain(predicate: "36")
        input.placeholder = "请输入药品"
        
        addBtn.centerYAlign(view: input)
        addBtn.leadingHorizontally(view: input)
        addBtn.trailingAlign(view: view, predicate: "-10")
        addBtn.setTitle("添加", for: UIControlState.normal)
        addBtn.backgroundColor = configure.shareConfigure.HMColor1
        addBtn.heightConstrain(predicate: "30")
        addBtn.layer.cornerRadius = 6
        addBtn.addTarget(self, action: #selector(addDrugs), for: UIControlEvents.touchUpInside)
        
        empty.topVertically(view: input, predicate: "25")
        empty.leadingHorizontally(view: input)
        empty.trailingAlign(view: view, predicate: "-10")
        empty.heightConstrain(predicate: "30")
        empty.setTitle("清空", for: UIControlState.normal)
        empty.backgroundColor = UIColor.gray
        empty.layer.cornerRadius = 6
        empty.addTarget(self, action: #selector(semptyDrugs), for: UIControlEvents.touchUpInside)
        
        describe.centerYAlign(view: empty)
        describe.text = "历史记录"
        describe.leadingAlign(view: view)
        describe.heightConstrain(predicate: "30")
        describe.width(view: input)
        
        //读取本地数据
        var dic:JSON
         dic =  drugsJson()
     
       /*
 "id":0,"desc":"任意"],["id":1,"desc":"dddddd"],["id":2,"desc":"任eeee意"],["id":3,"desc":"任eeeeeeeeeefff意"],["id":4,"desc":"任意"],["id":5,"desc":"任意eewefa"],["id":6,"desc":"任意asfaef"],["id":7,"desc":"任33333意"]
         */
        self.item = OptionItemView(self, json: dic)
        view.addSubview(item)
        item.setViews(sign: "历史记录",json: dic)
        let itemH = item.itemH
        item.topVertically(view: empty, predicate: "20")
        item.leadingAlign(view: view)
        item.trailingAlign(view: view)
        item.heightConstrain(predicate: "\(itemH)")
        item.buttonBlock =  {
            (dic) -> () in
            // 通过医生级别及交流方式获取价格
            let id = dic["id"] as! Int
            self.input.text = dic["desc"] as! String
        }

    }
    
    
    @objc func semptyDrugs(sender: UIButton){
        print("清除")
    }
    
    @objc func addDrugs(sender: UIButton) {
        print("添加")
        let plistName = getPlist()
        var mutAry = self.readToDrugsFile(file: plistName)
        mutAry.add(self.input.text as Any)

        // 过滤
        var newAry = mutAry as! Array<String>
        let se = Set<String>(newAry)
        newAry = Array(se)
        mutAry =  NSMutableArray.init(array: newAry)
        self.writeToDrugsFile(file: plistName, ary: mutAry)
        
        if self.drugsBlock != nil {
          self.drugsBlock!(self.input.text!)
        }
        
//        UserDefaults.standard.set(self.input.text, forKey: "DrugsName")
        self.navigationController?.popViewController(animated: true)
//        self.
//        let dic:JSON  = drugsJson()
//        self.item.setViews(sign: "历史记录",json: dic)
    }
    // plist
    
    func getPlist () -> String {
        //设置文件存放位置，配置文件一般比较重要，建议放在Document下，可ITunes同步
//        static let savePath = "\(NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, .UserDomainMask, true).first!)/MyConfig.plist"
        
        // Document / Caches
        let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
        
        let documentFilePath = paths.first
        
        // 拼接文件名
        let filePath = documentFilePath?.appending("/drugs.plist")
        
        return filePath!
    }
    // 将数组持久化到沙盒文件中
    func writeToDrugsFile(file:String, ary: NSMutableArray) {
        ary.write(toFile: file, atomically: true)
    }
    // 读取
    func readToDrugsFile(file: String) -> NSMutableArray {
        var ary = NSMutableArray.init(contentsOfFile: NSHomeDirectory() + "/Library/Caches/drugs.plist")
        
        if (ary == nil) {
            ary = NSMutableArray()
        }
        
        return ary!
    }
    
    func drugsJson() -> JSON {
        var dic:JSON
        let plistName = getPlist()
        let  aryData  =  self.readToDrugsFile(file: plistName)
        // 获取本地数据
        if aryData.count > 0 {
            var newDic = Dictionary<String, Any>()
            var newAry = Array<Any>()
            var i = 0
            for  ary in aryData {
                newDic["id"] = i
                newDic["desc"] = ary  as! String
                i += 1
                newAry.append(newDic)
            }
            dic = JSON.init(newAry)
        }else {
            dic = []
        }
        return dic
    }
}
